<template>
  <el-dialog v-if="load" title="设置列表字段" v-model="visible" align-center width="1200px" @close="handleClose" :close-on-click-modal="false">
    <div class="flex h-[600px]">
      <div class="left">
        <el-checkbox-group v-model="checkList">
          <div v-for="item in columnConfig.all" :key="item.label">
            <div class="label">{{ item.label }}</div>
            <div class="checkbox">
              <el-checkbox v-for="items in item.data" :key="items.label" :label="items.label" :value="items.value" class="w-[25%] mb-[8px] mr-0" />
            </div>
          </div>
        </el-checkbox-group>
      </div>

      <div class="right">
        <div class="text-[var(--base-sub-text-color)] px-[12px]">当前选定字段</div>
        <VueDraggable v-model="checkList">
          <div v-for="(item, idx) in checkList" :key="item" class="flex px-[8px] py-[6px]">
            <div class="dk-iconfont icon-Expand"></div>

            <div class="flex-1 mx-[4px]">
              {{ columnKeyValue[item] }}
            </div>
            <div class="dk-iconfont icon-Delete cursor-pointer" @click="dtlField(idx)"></div>
          </div>
        </VueDraggable>
      </div>
    </div>
    <template #footer>
      <!-- <div class="flex"> -->
      <el-button type="primary" @click="recoverDefault" style="float: left; margin-top: 12px">恢复默认</el-button>
      <el-button type="primary" :loading="loadings.submit" @click="submit" class="ml-auto">确认</el-button>
      <el-button @click="handleClose">取消</el-button>
      <!-- </div> -->
    </template>
  </el-dialog>
</template>
<script setup>
import { ElMessage } from "element-plus"
import { VueDraggable } from "vue-draggable-plus"
const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
const emit = defineEmits(["initTable"])
// 删除已选字段
const dtlField = (idx) => {
  checkList.value.splice(idx, 1)
}
const props = defineProps({
  api: { type: Function, default: () => ({}) },
  scope: { type: String, default: "" },
})

// 恢复默认配置
const recoverDefault = () => {
  checkList.value = columnConfig.value.default.map((v) => v.value)
}

const rules = reactive({
  value: [{ required: true, message: "请选择", trigger: "change" }],
})

const checkList = ref([])
const columnConfig = ref([])
const columnKeyValue = ref([])

// 打开弹窗
const open = async (params = {}) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  // 获取页面 列配置
  let configData = await props.api()
  columnConfig.value = configData.data
  columnKeyValue.value = columnConfig.value.all.map((v) => v.data).flat()
  columnKeyValue.value = Object.fromEntries(columnKeyValue.value.map((v) => [v.value, v.label]))

  // 用户配置项
  let userColumn = await getColumn()
  if (userColumn) {
    checkList.value = userColumn?.params?.map((v) => v.value)
  } else {
    // 用户无配置 使用默认配置
    recoverDefault()
  }
  loadings = reactive({})
  getColumn()
  visible.value = true
}

onMounted(async () => {})
// 关闭弹窗
const handleClose = () => {
  visible.value = false
}
// 提交
const submit = async () => {
  if (!checkList.value.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return
  }
  loadings.submit = true
  try {
    // 删除现有配置
    if (userColumnId.value) {
      await api.queryParamsDelete(`id=${userColumnId.value}`)
    }
    let params = {
      scope: props.scope,
      name: props.scope,
      params: checkList.value.map((v) => ({ llabel: columnKeyValue.value[v], value: v })),
    }

    api.queryParamsCreate(params).then((res) => {
      loadings.submit = false
      handleClose()
      emit("initTable", params)
    })
  } catch (error) {
    loadings.submit = false
  }
}

import api from "@/api/tableForm.js"

const getColumn = async () => {
  return await api.queryParamsIndex({ scope: props.scope }).then(async (res) => {
    userColumnId.value = res.data?.[0]?._id
    if (res.data.length) {
      return res.data?.[0]
    } else {
      let configData = await props.api()
      return {
        params: configData.data.default,
      }
    }

    return res.data?.[0] || null
  })
}
// 当前用户列配置id
const userColumnId = ref()
// 排序
const sortedArray = (columns = [], field = []) => {
  const sortedArray = field.reduce((acc, field) => {
    const item = columns.find((obj) => obj.field === field)
    if (item) acc.push(item)
    return acc
  }, [])
  return sortedArray
}

defineExpose({ open, getColumn, sortedArray })
</script>
<style lang="scss" scoped>
.left {
  .label {
    font-size: 16px;
    font-weight: bold;
    margin: 16px 0;
  }
  .checkbox {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
  }
}
.right {
  border-left: 1px solid var(--base-border-color);
  width: 360px;
}
</style>
